package com.able.concurrency.t4;

import java.util.Hashtable;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * @author abel.he
 * @data 2018/10/25 14:49
 * @describe Map同步容器
 * HashMap 底层通过Synchronized方法体实现
 * ConcurrentHashMap 代码块实现同步来实现
 * ConcurrentSkipListMap 有序的map方法，
 * ConcurrentHashMap/ConcurrentHashSet 底层哈希实现的同步 Map(Set)。效率高，线程安全。使用系统底层技术实现线程安全。量级较 synchronized 低。 key 和 value 不能为 null
 * ConcurrentSkipListMap/ConcurrentSkipListSet 底层跳表（SkipList） 实现的同步 Map(Set)。有序，效率比 ConcurrentHashMap 稍低
 */
public class Test1_ConcurrentMap {

    public static void main(String[] args) {
        final Map<String, String> map = new Hashtable<String, String>();
//        final Map<String, String> map = new ConcurrentHashMap<String, String>();
//        final Map<String, String> map = new ConcurrentSkipListMap<String, String>();

        final Random r = new Random();
        Thread[] threads = new Thread[100];
        final CountDownLatch countDownLatch = new CountDownLatch(threads.length);

        long beginTime = System.currentTimeMillis();

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 100000; j++) {
                        map.put("key" + r.nextInt(100000), "value" + r.nextInt(100000));
                    }
                    countDownLatch.countDown();
                }
            });
        }

        for (Thread thread :
                threads) {
            thread.start();
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("总共用时： " + (endTime - beginTime) + "ms");

    }

}
